var interval; // 记时器
var audio
Page({

  /**
   * 页面的初始数据
   */
  data: {
    history: true,
    buyed: false,
    collection: false,
    play: true,
    playindex: 0,
    historylist: [{
      play: true, // true 表示等待播放   false 表示正在播放
      totalmusic: 100, // 音频的总时长 秒值  需等待接口赋值
      seconds: 0, // 本地保存的秒值记录 ，进度条的值
      time: 0,
      total: '1:40', // 音频总时长 分秒值  等待接口赋值
      during: '00:00', // 音频的分秒值   显示在进度条左侧的数据
      playUrl: 'http://source.blistening.cn/bt_source/ttbt/audio/%E5%B0%8F%E9%A9%AC%E8%BF%87%E6%B2%B3.mp3'
    }, {
      play: true,
      totalmusic: 100,
      seconds: 0,
      time: 0,
      total: '1:40',
      during: '00:00',
      playUrl: 'http://source.blistening.cn/bt_source/ttbt/audio/%E5%B0%8F%E9%A9%AC%E8%BF%87%E6%B2%B3.mp3'
    }]
  },


  startplay: function() {
    var vm = this
    var list = vm.data.historylist;
    list[vm.data.playindex].play = false
    this.setData({
      historylist: list
    })

    audio.src = list[vm.data.playindex].playUrl;
    audio.title = list[vm.data.playindex].title
    audio.epname = list[vm.data.playindex].title
    audio.singer = list[vm.data.playindex].describe
    audio.coverImgUrl = list[vm.data.playindex].imageUrl
    audio.startTime = list[vm.data.playindex].seconds
    audio.play();
    audio.onCanplay(() => {
      // console.log(audio.duration)
    })
    audio.onPlay(() => {
      console.log('开始播放')
      var list2 = vm.data.historylist
      list2[vm.data.playindex].play = false;
      vm.setData({
        historylist: list2
      })
    })
    setTimeout(() => {
      console.log("音频长度" + Math.round(audio.duration))
      list[vm.data.playindex].totalmusic = Math.round(audio.duration)
      list[vm.data.playindex].total = getApp().s_to_hs(Math.round(audio.duration))
      vm.setData({
        historylist: list
      })
    }, 1000)

  },

  // 点击播放按钮 
  play: function(event) {
    var vm = this
    var id = event.currentTarget.dataset.id;
    // 播放一个音乐的时候如果其他在播放，停止其他定时器   
    clearInterval(interval)
    var index = event.currentTarget.dataset.index;
    var list = vm.data.historylist;
    for (var i = 0; i < list.length; i++) {
      // 把其他所有的音频都设置为等待播放状态 ，显示等待播放按钮
      list[i].play = true;
    }
    audio.pause();
    this.setData({
      historylist: list,
      playindex: index
    })
    vm.startplay()
    //提交浏览记录
    vm.torecord(id);
  },



  // 开启一个记时器，为当前音频计时显示在左侧秒值   并显示在进度条上
  startcount: function() {
    var vm = this
    // clearInterval(interval)
    interval = setInterval(function() {
      // 获取是否有上次播放的记录 并将保存的秒值转化成分秒值
      var during = getApp().s_to_hs(vm.data.historylist[vm.data.playindex].seconds)

      // 如果播放完成，停止计时并清空记录 
      if (vm.data.historylist[vm.data.playindex].seconds == vm.data.historylist[vm.data.playindex].totalmusic) {
        clearInterval(interval);
        vm.cleartime(vm.data.playindex);
        return
      }
      // 每秒更新左侧秒值和进度条值
      var list = vm.data.historylist;
      list[vm.data.playindex].during = during;
      list[vm.data.playindex].seconds = list[vm.data.playindex].seconds + 1;
      vm.setData({
        historylist: list
      })
      console.log(vm.data.historylist[vm.data.playindex].seconds);
    }, 1000)
  },

  // 进度条拖动联动
  slidechange: function(event) {
    var vm = this
    var index = event.currentTarget.dataset.index;
    var list = vm.data.historylist;
    var during = getApp().s_to_hs(event.detail.value)
    list[index].during = during;
    list[index].seconds = event.detail.value;
    audio.seek(event.detail.value)
    vm.setData({
      historylist: list
    })
  },

  // 播放完成清空左侧秒值  和  进度值
  cleartime: function(index) {
    var vm = this
    var list = vm.data.historylist;
    list[index].during = "00:00"; // 清空左侧秒值
    list[index].seconds = 0; // 清空进度值和本地记录
    list[index].play = !list[index].play
    this.setData({
      historylist: list
    })
  },


  // 点击暂停  停止计时并不清空左侧秒值和进度条， 显示播放按钮
  stop: function(event) {
    this.pauseaction()
    audio.pause();
  },


  pauseaction: function() {
    var vm = this
    var list = vm.data.historylist;
    list[vm.data.playindex].play = true
    this.setData({
      historylist: list
    })
    clearInterval(interval)
  },

  // 点击历史
  history: function() {
    this.setData({
      history: true,
      buyed: false,
      collection: false,
    })
    this.getdata(0)
  },

  // 点击已购
  buyed: function() {
    this.setData({
      history: false,
      buyed: true,
      collection: false,
    })
    this.getdata(1)
  },

  // 点击收藏
  collection: function() {
    this.setData({
      history: false,
      buyed: false,
      collection: true,
    })
    this.getdata(2)
  },

  // 猜你喜欢
  guess: function() {
    wx.navigateTo({
      url: './guess/guess',
    })
  },


  // 跳转详情页
  todetails: function(event) {
    var id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: './details/details?id=' + id,
    })
  },

  shareclick: function() {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var vm = this
    audio = wx.getBackgroundAudioManager();
    audio.onPlay(() => {
      console.log(111);
    })
    wx.onBackgroundAudioPlay(() => {
      // status	播放状态（2：没有音乐在播放，1：播放中，0：暂停中）
      wx.getBackgroundAudioPlayerState({
        success: function(res) {
          var status = res.status
          console.log("播放状态"+status)
          if (status == 1) {
            // vm.startcount();
          }else if(status==2){
            // vm.startcount();      
          }else{
            clearInterval(interval)
          }
        }
      })
    })
    audio.onPause(() => {
      console.log('音乐被暂停')
      vm.pauseaction();
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },



  torecord: function(ids) {
    var data = {
      "programId": ids,
      "status": 0,
      "userId": wx.getStorageSync("userId")
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/mark",
      "post", data, "",
      function(res) {
        if (res.code == 0) {
          console.log("已记录")
        }
      },
      function(res) {
        console.log(res)
      });
  },

  getdata: function(status) {
    var vm = this
    var data = {
      "startPoint": 0,
      "maxPage": 2
    }

    getApp().requestLoading(getApp().globalData.https + "programResource/status4Mark/" + wx.getStorageSync("userId") + "/" + status,
      "get", data, "加载中...",
      function(res) {
        for (var i = 0; i < res.data.result.length; i++) {
          res.data.result[i].play = true
          res.data.result[i].seconds = 0;
          res.data.result[i].during = "00:00";
          res.data.result[i].total = "--";
        }
        console.log(res.data);
        vm.setData({
          historylist: res.data.result
        })
      },
      function(res) {
        console.log(res)
      });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var vm = this
    // if (audio != null) {
    //   audio.play();
    // }
    if (vm.data.history) {
      vm.getdata(0)
    }

    if (vm.data.buyed) {
      vm.getdata(1)
    }

    if (vm.data.collection) {
      vm.getdata(2)
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // clearInterval(interval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("监听页面卸载")
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})